Previous | Chapter contents | Next | Book PDF
If you use the document architecture, some aspects of undo handling happen automatically. By default, each NSDocument has an NSUndoManager. (If you don't want your application supporting Undo, you can use NSDocument's setHasUndoManager: to prevent the creation of the undo manager.) You can use the setUndoManager: method if you need to use a subclass or if you otherwise need to change the undo manager used by the document.
When an NSDocument has an NSUndoManager, the document automatically keeps its edited state up to date by watching for notifications from the undo manager that tell it when changes are done, undone, or redone. In this case, you should never have to invoke NSDocument's updateChangeCount: method directly, since it is invoked automatically at the appropriate times.
The important thing to remember about supporting undo in a document-based application is that all changes that affect the persistent state of the document must be undoable. With a multilevel undo architecture, this is very important. If it is possible to make some changes to the document that cannot be undone, then the chain of edits that the NSUndoManager keeps for the document can become inconsistent with the document state. For example, imagine that you have a drawing program that is able to undo a resize, but not a delete. If the user selects a graphic and resizes it, the NSUndoManager gets an invocation that can undo that resize operation. Now the user deletes that graphic (which is not recorded for undo). If users now try to undo nothing would happen (at the very least) since the graphic that was resized is no longer there and undoing the resize can't have any visual effect. At worst, the application might crash trying to send a message to a freed object. So when you implement undo, remember that everything that causes a change to the document should be undoable.
Previous | Chapter contents | Next | Book PDF